package com.ry.est.controller;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ry.est.common.controller.BaseController;
import com.ry.est.constants.Constants;
import com.ry.est.dto.CommonResult;
import com.ry.est.entity.Users;
import com.ry.est.service.TokenService;
import com.ry.est.service.UserService;
import com.ry.est.util.ResultUtil;
import com.ry.est.util.WechatLoginProperties;
import com.ry.est.vo.TokenVo;
import com.ry.est.vo.UsersVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController extends BaseController {
    @Autowired
    private WechatLoginProperties wechatLoginProperties;

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @GetMapping("/login/wechat")
    public void wechatLogin() throws IOException {
        String url = wechatLoginProperties.getFullCodeUrl() ;
        response.sendRedirect(url);
    }

    @GetMapping("/login/wechatCallback")
    public void wechatCall(String code,String state) throws IOException {
        //发送获取accessToken的请求
        String getAccessTokenURL = wechatLoginProperties.getFullAccessTokenUrl(code);
        //获取accessToken和openId
        String accessTokenUrl = HttpUtil.get(getAccessTokenURL);
        JSONObject accessTokenJsonObj = JSONObject.parseObject(accessTokenUrl);
        String accessToken = accessTokenJsonObj.getString("access_token");
        String openid = accessTokenJsonObj.getString("openid");
        //根据openId查询用户是否已经存在
        Users users = userService.findByOpenId(openid);
        log.info(users.toString());
        //如果不存在，需要获取用户信息，进行自动注册
        if (null == users){
            String getUserInfoUrl = wechatLoginProperties
                    .getfullUserInfoUrl(accessToken,openid);
            String userInfoJsonString = HttpUtil.get(getUserInfoUrl);
            JSONObject userInfoJsonObj = JSONObject
                    .parseObject(userInfoJsonString);
            users = new Users();
            users.setUserName(userInfoJsonObj.getString("nickname"));
            users.setSex(userInfoJsonObj.getInteger("sex"));
            users.setIsAuthentication(Constants.EST_NOT);
            users.setFaceUrl(userInfoJsonObj.getString("headimgurl"));
            users.setOpenId(openid);
            Date createdTime = new Date();
            users.setCreatedTime(createdTime);
            users.setUpdatedTime(createdTime);
            users.setIsDelete(Constants.EST_NOT);

            userService.register(users);
        }
        TokenVo tokenVo = tokenService.generateToken(users);

        Map<String,String> map = new HashMap<>();
        map.put("token",tokenVo.getToken());
        map.put("userInfo",users.getUserName());

        log.info(map.toString());

        String s = JSON.toJSONString(map);
        String encode = URLEncoder.encode(s, "utf-8");

        log.info(s);

        log.info(wechatLoginProperties.getLoginSuccessUrl()+s);

        //返回登录成功的结果

        response.sendRedirect(wechatLoginProperties.getLoginSuccessUrl()+encode);
    }

    @PostMapping("/login/sms")
    public CommonResult<TokenVo> loginBySms(String phone,
                                            String sms){
        Users users = userService.loginBySms(phone,sms);
        TokenVo tokenVo = tokenService.generateToken(users);
        tokenService.saveToken(tokenVo.getToken(),users);
        return ResultUtil.success(tokenVo);
    }

    @GetMapping("/info")
    public CommonResult getUserInfo(){
        String token = request.getHeader("token");
        Users users = tokenService.getUserInfoByToken(token);
        UsersVO usersVO = new UsersVO();
        usersVO.setId(users.getId());
        usersVO.setAccount(users.getAccount());
        usersVO.setUsername(users.getUserName());
        usersVO.setSex(users.getSex());
        usersVO.setFaceUrl(users.getFaceUrl());
        usersVO.setToken(token);



        return ResultUtil.success(usersVO);
    }

}
